package com.example.sunmiv1.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.IndexDetailsAdapter;
import com.example.sunmiv1.entity.IndexDetailsBean;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class IndexDetailsActivity extends Activity {

    @BindView(R.id.indexDetails_startTime)
    TextView indexDetailsStartTime;
    @BindView(R.id.indexDetails_endTime)
    TextView indexDetailsEndTime;
    @BindView(R.id.indexDetails_listView)
    ListView indexDetailsListView;
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.indexDetails_query)
    ImageView indexDetailsQuery;
    @BindView(R.id.indexDetails_shopView)
    View indexDetailsShopView;
    @BindView(R.id.indexDetails_shopLayout)
    RelativeLayout indexDetailsShopLayout;
    @BindView(R.id.indexDetails_cashierView)
    View indexDetailsCashierView;
    @BindView(R.id.indexDetails_cashierLayout)
    RelativeLayout indexDetailsCashierLayout;
    @BindView(R.id.indexDetails_shopViewTv)
    TextView indexDetailsShopViewTv;
    @BindView(R.id.indexDetails_cashierViewTv)
    TextView indexDetailsCashierViewTv;
    private Context context;
    private IndexDetailsBean indexDetailsBean;
    private List<IndexDetailsBean.ListBean> list;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    private IndexDetailsAdapter indexDetailsAdapter;
    private int type = 1;//1:商城 2:收銀員


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    setIndexDetailsAdapter();
                    break;
                case 2:
                    setIndexDetailsAdapter();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_index_details);
        context = this;
        ButterKnife.bind(this);
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        titleTitle.setText(R.string.indexDetailsTitle);
        list = new ArrayList<>();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
        Date date = new Date(System.currentTimeMillis()); // 獲取當前時間
        indexDetailsStartTime.setText(simpleDateFormat.format(date));
        indexDetailsEndTime.setText(simpleDateFormat.format(date));
        getIndexDetails();
    }

    private void setIndexDetailsAdapter() {
        if (indexDetailsAdapter == null) {
            indexDetailsAdapter = new IndexDetailsAdapter(context, list);
            indexDetailsListView.setAdapter(indexDetailsAdapter);
        } else {
            indexDetailsAdapter.notifyDataSetChanged();
        }
    }

    @OnClick({R.id.title_back, R.id.indexDetails_startTime, R.id.indexDetails_endTime, R.id.indexDetails_query,
            R.id.indexDetails_shopLayout, R.id.indexDetails_cashierLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.indexDetails_shopLayout:
                type = 1;
                indexDetailsShopView.setVisibility(View.VISIBLE);
                indexDetailsCashierView.setVisibility(View.GONE);
                indexDetailsShopViewTv.setTextColor(getResources().getColorStateList(R.color.text_333));
                indexDetailsCashierViewTv.setTextColor(getResources().getColorStateList(R.color.text_999));
                list.clear();
                setIndexDetailsAdapter();
                getIndexDetails();
                break;
            case R.id.indexDetails_cashierLayout:
                type = 2;
                indexDetailsShopView.setVisibility(View.GONE);
                indexDetailsCashierView.setVisibility(View.VISIBLE);
                indexDetailsShopViewTv.setTextColor(getResources().getColorStateList(R.color.text_999));
                indexDetailsCashierViewTv.setTextColor(getResources().getColorStateList(R.color.text_333));
                list.clear();
                setIndexDetailsAdapter();
                getIndexDetails();
                break;
            case R.id.title_back:
                finish();
                break;
            case R.id.indexDetails_startTime:
                getDateFromDatePickerDialog(indexDetailsStartTime);
                break;
            case R.id.indexDetails_endTime:
                getDateFromDatePickerDialog(indexDetailsEndTime);
                break;
            case R.id.indexDetails_query:
                list.clear();
                setIndexDetailsAdapter();
                getIndexDetails();
                break;
        }
    }

    // 加載數據
    private void getIndexDetails() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("needsellinfo", "1");
            jsonObject.put("operator_identity_id", aCache.getAsString("uid"));
            if ("3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            }
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject.put("starttime", indexDetailsStartTime.getText().toString());
            jsonObject.put("endtime", indexDetailsEndTime.getText().toString());
            String url = "";
            if (type == 1) {
                url = Common.GET_INDEX_DETAILS_SHOP;
            } else {
                url = Common.GET_INDEX_DETAILS_CASHIER;
            }
//            url = Common.GET_INDEX_DETAILS;
            HttpUtils.post(context, url, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    indexDetailsBean = GsonUtils.JsonToBean(text, IndexDetailsBean.class);
                    Message msg = new Message();
                    if (indexDetailsBean.getStatus() == 1) {
                        list.clear();
//                        for (IndexDetailsBean.ListBean bean : indexDetailsBean.getList()) {
//                            if (type == 1) {
//                                if (bean.getId() == 0) {
//                                    list.add(bean);
//                                }
//                            } else {
//                                if (bean.getId() != 0) {
//                                    list.add(bean);
//                                }
//                            }
//                        }
                        list.addAll(indexDetailsBean.getList());
                        msg.what = 1;
                    } else {
//                        loadingDialog.dismiss();
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 點擊某個textView，調起時間選擇器，設置該時間選擇器返回的時間給該textView
     *
     * @param tv textView
     */
    private void getDateFromDatePickerDialog(TextView tv) {
        Calendar calendar = Calendar.getInstance();
        new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            // 綁定監聽器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此處得到選擇的時間，可以進行你想要的操作
                if ((monthOfYear + 1) < 10) {
                    tv.setText(year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth);
                } else {
                    tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                }
            }
        }// 設置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

}
